<?php
namespace Home\Model;
use Think\Model;

class OrderInfoModel extends CommonModel {
	public function _initialize() {
		parent::_initialize();
		$this->udaSrv            = D('UserDeliveryAddress');
		$this->cartSrv           = D('CartTmp');
		$this->commodityLimitSrv = D('CommodityLimit');
		$this->commoditySrv      = D('CommodityInfo');
		$this->commoditySrv->ini();
	}

	public function addCommonOrder($user_id, $dispatch_datetime, $uda_id) {
		//验证购物车信息、库存和配送时间
		$res = $this->cartSrv->getCartList($user_id);
		if ($res['isok'] == false) {
			return $res;
		}

		$cart_list = $res['data'];
		//检查库存 选择配送期
		$new_commoditys = array();
		foreach ($cart_list['list'] as $commodity) {
			$check = $this->commodityLimitSrv->checkLimit($commodity['commodity_id'], $commodity['commodity_num'], 1);
			if ($check == false) {
				$res2['isok'] = false;
				$res2['msg']  = $commodity['name'] . "库存不足";
				return $res2;
			}
			$sale_cycle = $this->commoditySrv->hitLastSaleCycle($commodity['commodity_id']);
			if ($sale_cycle['dispatch_datetime'] != $dispatch_datetime) {
				$res2['isok'] = false;
				$res2['msg']  = '配送时间有误';
				return $res2;
			}
		}
		//验证配送地址
		$uda_info = $this->udaSrv->where("uda_id = '" . $uda_id . "'")->find();
		if (empty($uda_info)) {
			$res2['isok'] = false;
			$res2['msg']  = '配送地址有误';
			return $res2;
		}
		//整理插入数据
		//order_info
		$order_info['order_id']          = new_doc_id('ORDER');
		$order_info['order_type']        = 'common';
		$order_info['user_id']           = $user_id;
		$order_info['dispatch_datetime'] = $dispatch_datetime;
		$order_info['collect_datetime']  = $sale_cycle['collect_datetime'];
		$order_info['order_status']      = C('ORDER_STATUS.WAITING_PROCESS');
		//order_detail
		$order_details = array();
		foreach ($cart_list['list'] as $commodity) {
			$detail_one                        = array();
			$detail_one['order_id']            = $order_info['order_id'];
			$detail_one['commodity_id']        = $commodity['commodity_id'];
			$detail_one['commodity_type']      = 'common';
			$detail_one['order_num']           = $commodity['commodity_num'];
			$detail_one['original_sale_price'] = $commodity['sale_price'];
			$detail_one['settle_price']        = $commodity['sale_price'];
			$order_details[]                   = $detail_one;
		}
		//order_ship
		$order_ship['ship_id']  = new_doc_id('ORDER_SHIP');
		$order_ship['order_id'] = $order_info['order_id'];
		$order_ship['consignee'] = $uda_info['consignee'];
		$order_ship['city']     = $uda_info['city'];
		$order_ship['district'] = $uda_info['district'];
		$order_ship['address']  = $uda_info['address'];
		$order_ship['zipcode']  = $uda_info['zipcode'];
		$order_ship['mobile']   = $uda_info['mobile'];
		//payment_info
		$payment_info['payment_id']         = new_doc_id('PAYMENT');
		$payment_info['order_id']           = $order_info['order_id'];
		$payment_info['commoditys_payment'] = num_f($cart_list['sum']['sale_sum']);
		$payment_info['shipping_payment']   = $this->getShippingFee($payment_info['commoditys_payment']);
		$payment_info['should_payment']     = num_f($payment_info['commoditys_payment'] + $payment_info['shipping_payment']);
		$payment_info['payment_status']     = C('PAYMENT_STATUS.WAITING_PAY');
		$payment_info['payment_type']       = C('PAYMENT_TYPE.WAITING_CHOOSE');
		$this->addOrder($order_info, $order_details, $order_ship, $payment_info);
		//清楚购物车数据
		$this->cartSrv = D('CartTmp');
		$this->cartSrv->deleteCartAll($user_id);
		return array('isok' => true, 'order_id' => $order_info['order_id'],'payment_id'=>$payment_info['payment_id'],'should_payment'=>$payment_info['should_payment']);
	}

	public function addGrouponOrder($cart_list, $user_id, $dispatch_datetime, $uda_id, $set_id, $gpon_id, $ship_fee) {
		//检查库存 选择配送期
		$new_commoditys = array();
		foreach ($cart_list['list'] as $commodity) {
			$check = $this->commodityLimitSrv->checkLimit($commodity['commodity_id'], $commodity['commodity_num'], 2);
			if ($check == false) {
				$res2['isok'] = false;
				$res2['msg']  = $commodity['name'] . "库存不足";
				return $res2;
			}
			$sale_cycle = $this->commoditySrv->hitLastSaleCycle($commodity['commodity_id']);
			if ($sale_cycle['dispatch_datetime'] != $dispatch_datetime) {
				$res2['isok'] = false;
				$res2['msg']  = '配送时间有误';
				return $res2;
			}
		}
		//验证配送地址
		$uda_info = $this->udaSrv->where("uda_id = '" . $uda_id . "'")->find();
		if (empty($uda_info)) {
			$res2['isok'] = false;
			$res2['msg']  = '配送地址有误';
			return $res2;
		}
		//整理插入数据
		//order_info
		$order_info['order_id']          = new_doc_id('ORDER');
		$order_info['order_type']        = 'groupon';
		$order_info['user_id']           = $user_id;
		$order_info['dispatch_datetime'] = $dispatch_datetime;
		$order_info['collect_datetime']  = $sale_cycle['collect_datetime'];
		$order_info['order_status']      = C('ORDER_STATUS.WAITING_PROCESS');
		$order_info['promote_id']        = $set_id;
		$order_info['promote_code']      = $gpon_id;
		//order_detail
		$order_details = array();
		foreach ($cart_list['list'] as $commodity) {
			$detail_one                        = array();
			$detail_one['order_id']            = $order_info['order_id'];
			$detail_one['commodity_id']        = $commodity['commodity_id'];
			$detail_one['commodity_type']      = 'groupon';
			$detail_one['order_num']           = $commodity['commodity_num'];
			$detail_one['original_sale_price'] = $commodity['sale_price'];
			$detail_one['settle_price']        = $commodity['sale_price'];
			$order_details[]                   = $detail_one;
		}
		//order_ship
		$order_ship['ship_id']  = new_doc_id('ORDER_SHIP');
		$order_ship['order_id'] = $order_info['order_id'];
		$order_ship['consignee'] = $uda_info['consignee'];
		$order_ship['city']     = $uda_info['city'];
		$order_ship['district'] = $uda_info['district'];
		$order_ship['address']  = $uda_info['address'];
		$order_ship['zipcode']  = $uda_info['zipcode'];
		$order_ship['mobile']   = $uda_info['mobile'];
		//payment_info
		$payment_info['payment_id']         = new_doc_id('PAYMENT');
		$payment_info['order_id']           = $order_info['order_id'];
		$payment_info['commoditys_payment'] = num_f($cart_list['sum']['sale_sum']);
		$payment_info['shipping_payment']   = $ship_fee;
		$payment_info['should_payment']     = num_f($payment_info['commoditys_payment'] + $payment_info['shipping_payment']);
		$payment_info['payment_status']     = C('PAYMENT_STATUS.WAITING_PAY');
		$payment_info['payment_type']       = C('PAYMENT_TYPE.WAITING_CHOOSE');
		$this->addOrder($order_info, $order_details, $order_ship, $payment_info);
		//占库存
		$commodityLimit = D('CommodityLimit');
		foreach ($order_details as $one) {
			$commodityLimit->doLimitByOrder($order_info['order_id'], $one['commodity_id'], $one['order_num'], 2, -1);
		}
		return array('isok' => true, 'order_id' => $order_info['order_id'],'payment_id'=>$payment_info['payment_id'],'should_payment'=>$payment_info['should_payment']);
	}

	public function addOrder($order_info, $order_details, $order_ship, $payment_info) {
		$this->data($order_info)->add();
		$orderDetailSrv = D('OrderDetail');
		foreach ($order_details as $detail_one) {
			$orderDetailSrv->data($detail_one)->add();
		}
		$orderShipSrv = D('OrderShip');
		$orderShipSrv->data($order_ship)->add();
		$paymentInfoSrv = D('PaymentInfo');
		$paymentInfoSrv->data($payment_info)->add();
	}

	public function getShippingFee($commoditys_payment) {
		if ($commoditys_payment >= C('FREE_SHIPPING_OVER')) {
			return 0;
		} else {
			return C('DEFAULT_SHIPPING_FEE');
		}
	}

	public function getOrderList($user_id, $order_page,$payment_status,$pageno, $pagesize) {
		$limit  = ($pageno - 1) * $pagesize . "," . $pagesize;
		$order_where = "";
		if($order_page == 1){
			$order_where = " oi.order_status <> 20";
		}else{
			$order_where = " oi.order_status = 20";
		}
		if(!empty($payment_status)){
			$order_where .= " and pi.payment_status = '".$payment_status."'";
		}
		$db_res = $this->query("SELECT oi.*,pi.should_payment,pi.payment_status FROM ar_shop.order_info AS oi
		LEFT JOIN ar_shop.payment_info AS pi ON pi.order_id = oi.order_id
		WHERE oi.user_id = '" . $user_id . "' and ".$order_where."
		ORDER BY oi.insert_time DESC
		LIMIT " . $limit);
		if (empty($db_res)) {
			return null;
		}
		$db_count = $this->query("SELECT count(*) as rows_count FROM ar_shop.order_info AS oi
		LEFT JOIN ar_shop.payment_info AS pi ON pi.order_id = oi.order_id
		WHERE oi.user_id = '" . $user_id . "' and ".$order_where);
		$rows_count = num_f($db_count[0]['rows_count']);
		
		$new_list = null;
		foreach ($db_res as $db_one) {
			$db_one['order_status_name']   = C('ORDER_STATUS_NAME.' . $db_one['order_status']);
			$db_one['payment_status_name'] = C('PAYMENT_STATUS_NAME.' . $db_one['payment_status']);
			$db_res2 = $this->query("SELECT od.commodity_id,od.order_num,ci.`name`,CONCAT('".C('HTTP_IMG')."',cpi.brief_pic) as brief_pic FROM ar_shop.order_detail as od 
			LEFT JOIN ar_shop.commodity_info as ci on ci.commodity_id = od.commodity_id 
			LEFT JOIN ar_shop.commodity_pic_info as cpi on cpi.commodity_id = ci.commodity_id
			where od.order_id = '".$db_one['order_id']."' AND cpi.type = 1");
			
			$db_one['order_commoditys'] = $db_res2;
			$new_list[]           = $db_one;
		}
		$res['list'] = $new_list;
		$res['page_info']['rows_count'] = $rows_count;
		$res['page_info']['pageno'] = $pageno;
		$res['page_info']['pagesize'] = $pagesize;
		return $res;
	}

	public function getOrderInfo($order_id, $user_id) {
		$db_res = $this->query("SELECT * FROM ar_shop.order_detail AS od
		LEFT JOIN ar_shop.order_info AS oi ON oi.order_id = od.order_id
		LEFT JOIN ar_shop.commodity_info AS ci ON ci.commodity_id = od.commodity_id
		LEFT JOIN ar_shop.payment_info AS pi ON pi.order_id = od.order_id
		LEFT JOIN ar_shop.order_ship AS os ON os.order_id = od.order_id
		LEFT JOIN ar_shop.address_city AS ac ON ac.city_id = os.city
		LEFT JOIN ar_shop.address_district AS ad ON ad.region_id = os.district
		LEFT JOIN ar_shop.commodity_pic_info AS cpi ON cpi.commodity_id = od.commodity_id
		WHERE oi.order_id = '" . $order_id . "' AND oi.user_id = '" . $user_id . "' and cpi.type=1");
		if (empty($db_res)) {
			return null;
		}

		$order_info       = null;
		$order_commoditys = null;
		$payment_info     = null;
		foreach ($db_res as $db_one) {
			$order_info['order_id']          = $db_one['order_id'];
			$order_info['order_type']        = $db_one['order_type'];
			$order_info['dispatch_datetime'] = $db_one['dispatch_datetime'];
			$order_info['order_status']      = $db_one['order_status'];
			$order_info['order_status_name'] = C('ORDER_STATUS_NAME.' . $db_one['order_status']);

			$payment_info['payment_id']          = $db_one['payment_id'];
			$payment_info['commoditys_payment']  = $db_one['commoditys_payment'];
			$payment_info['shipping_payment']    = $db_one['shipping_payment'];
			$payment_info['card_payment']        = $db_one['card_payment'];
			$payment_info['should_payment']      = $db_one['should_payment'];
			$payment_info['real_payment']        = $db_one['real_payment'];
			$payment_info['payment_status']      = $db_one['payment_status'];
			$payment_info['payment_status_name'] = C('PAYMENT_STATUS_NAME.' . $db_one['payment_status']);
			$payment_info['payment_type']        = $db_one['payment_type'];
			$payment_info['payment_type_name']   = C('PAYMENT_TYPE_NAME.' . $db_one['payment_type']);
			$payment_info['success_pay_time']    = $db_one['success_pay_time'];
			
			$ship_info['ship_id'] = $db_one['ship_id'];
			$ship_info['city_name'] = $db_one['city_name'];
			$ship_info['region_name'] = $db_one['region_name'];
			$ship_info['address'] = $db_one['address'];
			$ship_info['mobile'] = $db_one['mobile'];
			$ship_info['consignee'] = $db_one['consignee'];

			$order_detail['commodity_id']   = $db_one['commodity_id'];
			$order_detail['name']           = $db_one['name'];
			$order_detail['commodity_type'] = $db_one['commodity_type'];
			$order_detail['order_num']      = $db_one['order_num'];
			$order_detail['settle_price']   = $db_one['settle_price'];
			$order_detail['brief_pic']   = C('HTTP_IMG').$db_one['brief_pic'];
			$order_commoditys[]             = $order_detail;
		}
		return array('order_info' => $order_info, 'payment_info' => $payment_info, 'order_commoditys' => $order_commoditys ,'ship_info'=>$ship_info);
	}
	
	// 取消订单
	public function cancelOrder($order_id,$user_id){
		if(empty($user_id)){
			$order_info = $this->where("order_id = '".$order_id."'")->find();
		}else{
			$order_info = $this->where("order_id = '".$order_id."' and user_id = '".$user_id."'")->find();
		}
		if(empty($order_info)){
			$res['isok'] = false;
			$res['isok'] = '没有找到该订单';
			return $res;
		}
		if($order_info['order_status']!=C('ORDER_STATUS.WAITING_PROCESS')){
			$res['isok'] = false;
			$res['isok'] = '订单不能取消';
			return $res;
		}
		$paymentInfo = D('PaymentInfo');
		$payment_info = $paymentInfo->where("order_id = '".$order_id."'")->find();
		if($payment_info['payment_status']==C('PAYMENT_STATUS.PAYED_CLOSE')){
			$res['isok'] = false;
			$res['isok'] = '订单已经支付不能取消';
			return $res;
		}
		$orderDetail = D('OrderDetail');
		if($order_info['order_type']=='groupon'){//团购订单，取消订单需要减库存
			$db_res = $orderDetail->where("order_id = '".$order_id."'")->select();
			//取消后 加库存
			$commodityLimit = D('CommodityLimit');
			foreach($db_res as $db_one){// 普通商品 减库存
				$commodityLimit->doLimitByOrder($db_one['order_id'],$db_one['commodity_id'],$db_one['order_num'],2,1);
			}
		}
		$this->where("order_id = '".$order_id."'")->save(array('order_status'=>20));
		
		$res['isok'] = true;
		$res['isok'] = '订单取消成功';
		return $res;
	}
}

?>